<?php

namespace app\manystore\controller\my;

use app\common\controller\ManystoreBase;
use app\common\library\Ems;
use app\common\library\Sms;
use fast\Random;
use think\Config;
use think\Validate;

use think\Db;
use app\manystore\Model\ManystoreModel;
use app\manystore\Model\CampusClassCourseArranging;
use app\manystore\Model\BroadcastLog;
use app\manystore\Model\CampusClassCourseDate;
use app\manystore\Model\CampusClewConsultantModel;
use app\manystore\Model\CampusClassRecord;
use app\manystore\Model\User;
use app\manystore\Model\ManystoreShop;
use app\manystore\Model\AddService;
use app\manystore\Model\ManystoreRecommendRecord;
use app\manystore\Model\ManystoreAuthGroup;
use app\manystore\Model\ManystoreInformation;
use app\manystore\Model\TypeModel;
use app\manystore\Model\AppreciationServe;
use app\manystore\Model\ManystoreOrderRecord;

/**
 * 我的接口
 */
class My extends ManystoreBase
{
    protected $noNeedLogin = ['login','getWinningRecord'];
    protected $noNeedRight = '*';
    protected $auth = [];

    public function _initialize()
    {
        parent::_initialize();
    }

    /**
     * 商户登录
     *
     * @ApiMethod (POST)
     * @param string $account  账号
     * @param string $password 密码
     */
    public function login()
    {
        $account = $this->request->post('account');
        $password = $this->request->post('password');
        if (!$account || !$password) {
            $this->error(__('Invalid parameters'));
        }

        $ret = $this->auth->login($account, $password);


        if ($ret) {
            $data = ['userinfo' => $this->auth->getUserinfo()];
            $this->success(__('Logged in successful'),'', $data);
        } else {
            $this->error($this->auth->getError());
        }
    }

    /**
     * 获取我的信息
     *
     * @ApiMethod (GET)
     * @ApiTitle    获取我的信息

     * @ApiParams (name="type", type="integer", required=false, description="0不获取统计信息 1今日 2本周 3上周 4本月 5上月")

     * @ApiSector   我的接口
     * @ApiReturn   ({
          "code": 1,
          "msg": "获取数据成功",
          "time": "1657984618",
          "data": null
        })
     */
    public function getMyInfo()
    {
        $user = $this->auth->getUserinfo();

        $type = intval($this->request->param('type'));//1今日 2本周 3上周 4本月 5上月 6全部

        if($type == 1)
        {
            $start_time = strtotime(date('Y-m-d').' 00:00:00');
            $end_time = strtotime(date('Y-m-d').' 23:59:59');
        }
        else if($type == 2)
        {
            $start_time = strtotime(date("Y-m-d H:i:s", mktime(0,0,0,date("m"),date("d")-date("w")+1,date("Y"))));
            $end_time = strtotime(date("Y-m-d H:i:s", mktime(23,59,59,date("m"),date("d")-date("w")+7,date("Y"))));
        }
        else if($type == 3)
        {
            $start_time = strtotime(date('Y-m-d H:i:s', mktime(0,0,0,date('m'),date('d')-date('w')+1-7,date('Y'))));
            $end_time = strtotime(date('Y-m-d H:i:s', mktime(23,59,59,date('m'),date('d')-date('w')+7-7,date('Y'))));
        }
        else if($type == 4)
        {
            $start_time = strtotime(date('Y-m').'-01 00:00:00');
            $end_time = strtotime(date('Y-m-01',strtotime(date("Y-m-d"))) . "23:59:59 +1 month -1 day");
        }
        else if($type == 5)
        {
            $start_time = strtotime(date('Y-m-01', strtotime('-1 month')).' 00:00:00');
            $end_time = strtotime(date('Y-m-t', strtotime('-1 month')).' 23:59:59');
        }
        else if($type == 6)
        {
            $start_time = 1;
            $end_time = time();
        }

        $teacher_other = [];
        $consultant_other = [];

        if(!empty($start_time) && $user['level'] == 2)
        {
            $teacher_other = [
                'class_hour_teacher' => 0,//老师授课课时
                'class_hour_student' => 0,//学员消耗课时
                'price_student' => 0,//学员课消金额
                'attend_class' => 0,//学员到课人/次
                'leave' => 0,//学员请假人/次
                'absenteeism' => 0,//学员未到人/次
                'make_up_lessons' => 0,//学员缺课已补人/次
                'audition_student' => 0,//到课试听类型学员
                'make_up_lessons_student' => 0,//到课补课类型学员
            ];

            //课时统计            
            $class_hour_list = CampusClassRecord::field('COUNT(ccr.id) AS count,SUM(cccd.class_hour) AS class_hour,ccr.m_type,SUM(ccr.m_type_num) AS m_type_num,SUM(price) AS price,cccs.status AS sign_status,cccs.remedial_status as make_up_lessons_status,cccs.type AS sign_type')
                ->alias('ccr')
                ->join('ss_campus_class_course_sign cccs','cccs.id = ccr.sign_id')
                ->join('ss_campus_class_course_date cccd','cccd.id = cccs.d_id')
                ->join('ss_campus_class_student ccs','ccs.user_id = ccr.user_id')
                ->where(function($query) use ($user){
                    $query->whereOr('cccd.teacher_id','like',"%,{$user['id']},%")
                        ->whereOr('cccd.teacher_id','like',"{$user['id']},%")
                        ->whereOr('cccd.teacher_id','like',"%,{$user['id']}")
                        ->whereOr('cccd.teacher_id',"{$user['id']}");
                })
                ->where(['ccr.style' => 1,'ccr.status' => 1,'ccr.createtime' => ['BETWEEN',[$start_time,$end_time]]])
                ->group('ccr.m_type,cccs.status,cccs.remedial_status')
                ->select();

            foreach ($class_hour_list as $key => $value)
            {
                //老师授课课时
                $teacher_other['class_hour_teacher'] += $value['class_hour'];
                //学员消耗课时
                if($value['m_type'] == 'hour')
                {
                    $teacher_other['class_hour_student'] += $value['m_type_num'];
                }
                else if($value['m_type'] == 'monthly')
                {
                    $teacher_other['class_hour_student'] += bcmul($value['m_type_num'],30 * 24,2);
                }
                else if($value['m_type'] == 'day')
                {
                    $teacher_other['class_hour_student'] += bcmul($value['m_type_num'],24,2);
                }
                //学员课消金额
                $teacher_other['price_student'] += $value['price'];
                //学员到课人/次
                if($value['sign_status'] == 1)
                {
                    $teacher_other['attend_class'] += $value['count'];
                }
                //学员请假人/次
                else if($value['sign_status'] == 3)
                {
                    $teacher_other['leave'] += $value['count'];
                }
                //学员未到人/次
                else if($value['sign_status'] == 2)
                {
                    $teacher_other['absenteeism'] += $value['count'];
                }
                //学员缺课已补人/次
                if($value['sign_status'] == 1 && $value['make_up_lessons_status'] == 1)
                {
                    $teacher_other['make_up_lessons'] += $value['count'];
                }
                //到课试听类型学员
                if($value['sign_type'] == 3)
                {
                    $teacher_other['audition_student'] += $value['count'];
                }
                //到课补课类型学员
                if($value['sign_type'] == 2)
                {
                    $teacher_other['make_up_lessons_student'] += $value['count'];
                }
            }
        }

        if(!empty($start_time) && $user['course_consultant'] == 1)
        {
            $consultant_other = [
                'clue' => 0,//线索数
                'follow_up' => 0,//跟进数
                'enter_the_store' => 0,//到店人数
                'audition' => 0,//试听人数
                'new_registration' => 0,//新报人数
                'renewal_of_registration' => 0,//续报人数
                'deal' => 0,//成交人数
                'sales_amount' => 0,//销售金额
            ];

            $sales_data_statistics = User::field('COUNT(cco.id) AS count,ccos.enroll_type,u.student_type,cco.price,cco.num')
            ->alias('u')
            ->join('ss_campus_course_order cco','cco.user_id = u.id and cco.status = 2')
            ->join('ss_campus_course_order_sublevel ccos','ccos.gs_id = cco.id')
            ->where(function($query) use ($user){
                $query->whereOr('u.course_consultant',$user['id'])
                    ->whereOr('u.follow_uid',$user['id']);
            })
            ->group('u.student_type,ccos.enroll_type')
            ->select();

            foreach ($sales_data_statistics as $key => $value)
            {
                //线索数（为顾问时计入）
                if($value['course_consultant'] == $user['id'] && $value['student_type'] == 0)
                {
                    $consultant_other['clue'] ++;
                }

                //跟进数
                if($value['follow_uid'] == $user['id'])
                {
                    $consultant_other['follow_up'] ++;
                }

                //试听人数（为顾问时计入）
                if($value['course_consultant'] == $user['id'] && $value['student_type'] == 1)
                {
                    $consultant_other['audition'] ++;
                }

                //新报人数
                if($value['enroll_type'] == 1)
                {
                    $consultant_other['new_registration'] ++;
                }
                //续报人数
                else if($value['enroll_type'] == 2)
                {
                    $consultant_other['new_registration'] ++;
                }

                //成交人数
                $consultant_other['deal'] ++;

                //销售金额
                $consultant_other['sales_amount'] += bcmul($value['price'],$value['num'],2);
            }
        }

        //查询机构名称
        $mechanism = ManystoreModel::where(['shop_id' => $user['shop_id'],'is_main' => 1])->value('username');

        //查询角色名称
        $role = ManystoreAuthGroup::where('id',$user['group_selfid'])->value('name');



        $data = [
            'id' => $user['id'],
            'avatar' => $user['avatar'],
            'name' => $user['username'],
            'mobile' => $user['mobile'],
            'username' => $user['username'],
            'nickname' => $user['nickname'],
            'level' => $user['nickname'],//类型：0=服务商,1=校区,2=老师
            'role' => $role,//角色
            'teacher_other' => $teacher_other,//老师其他附加信息
            'consultant_other' => $consultant_other,//顾问其他附加信息
            'mechanism' => $mechanism,
        ];

        $this->success('获取数据成功','',$data);
    }

    /**
     * 修改我的信息
     *
     * @ApiMethod (POST)
     * @ApiTitle    修改我的信息

     * @ApiParams (name="avatar", type="string", required=false, description="头像路径【根据上传接口返回值】")
     * @ApiParams (name="nickname", type="string", required=false, description="昵称")

     * @ApiSector   我的接口
     * @ApiReturn   ({
          "code": 1,
          "msg": "获取数据成功",
          "time": "1657984618",
          "data": null
        })
     */
    public function updateMyInfo()
    {
        $user = $this->auth->getUserinfo();

        $manystoreModel = ManystoreModel::get($user['id']);

        $avatar = $this->request->post('avatar');//头像路径
        $nickname = $this->request->post('nickname');//昵称

        $update = [];

        if(!empty($avatar))
        {
            if(!is_file('.'.$avatar))
            {
                $this->error('请上传头像');
            }

            $manystoreModel->avatar = $avatar;
        }

        if(!empty($nickname))
        {
            $manystoreModel->nickname = $nickname;
        }


        

        // 启动事务
        Db::startTrans();
        try
        {
            $ret = $manystoreModel->save();

            // 提交事务
            Db::commit();
        }
        catch (\Exception $e)
        {
            // 回滚事务
            Db::rollback();
            $this->error('更新信息失败');
        }

        $this->success('更新信息成功','');
    }

    /**
     * 获取短信余数
     *
     * @ApiMethod (GET)
     * @ApiTitle    获取短信余数

     * @ApiSector   我的接口
     * @ApiReturn   ({
          "code": 1,
          "msg": "获取数据成功",
          "time": "1657984618",
          "data": null
        })
     */
    public function getNumOfMsg()
    {
        $user = $this->auth->getUserinfo();

        if(empty($user['shop_id']))
        {
            $this->error('非商家无权限使用该服务');
        }

        $shop_info = ManystoreShop::get($user['shop_id']);

        $data = [
            'msm_num' => $shop_info->sms_num,
        ];

        $this->success('获取数据成功','',$data);
    }

    /**
     * 获取增值服务
     *
     * @ApiMethod (GET)
     * @ApiTitle    获取增值服务

     *  @ApiParams (name="type", type="integer", required=false, description="类型:1=天誉系统;2=在线直播;3=国内通用短信包;4=营销中心;5=在线课程,多项以逗号分隔")

     * @ApiSector   我的接口
     * @ApiReturn   ({
          "code": 1,
          "msg": "获取数据成功",
          "time": "1657984618",
          "data": null
        })
     */
    public function getAddServiceList()
    {
        $user = $this->auth->getUserinfo();

        $type = $this->request->param('type');
        $type = explode(',', $type);
        foreach($type as & $v)
        {
            $v = intval($v);
        }

        if(empty($user['shop_id']))
        {
            $this->error('非商家无权限');
        }

        $goods = AddService::field('title,image,describe,num,unit_price,price,content')->where(['type' => ['in',$type],'status' => 1])->select();

        $data = [
            'goods' => $goods,
        ];

        $this->success('获取数据成功','',$data);
    }

    /**
     * 获取开通或未开通的增值服务
     *
     * @ApiMethod (GET)
     * @ApiTitle    获取开通或未开通的增值服务

     *  @ApiParams (name="type", type="integer", required=false, description="类型:0=未开通，1=已开通")

     * @ApiSector   我的接口
     * @ApiReturn   ({
          "code": 1,
          "msg": "获取数据成功",
          "time": "1657984618",
          "data": null
        })
     */
    public function getAddServiceList2()
    {
        $user = $this->auth->getUserinfo();

        if(empty($user['shop_id']))
        {
            $this->error('非商家无权限');
        }

        $type = $this->request->param('type');
        $type = $type == 1 ? 1 : 0;

        $shop_info = ManystoreShop::get($user['shop_id']);

        $types = [];

        if($type == 1)
        {
            //直播
            if($shop_info['live_day'] > 0)
            {
                $types[] = 2;
            }

            //营销
            if($shop_info['market_day'] > 0)
            {
                $types[] = 4;
            }

            //课程【没有该字段余数，后面添加】
        }
        else
        {
            //直播
            if($shop_info['live_day'] == 0)
            {
                $types[] = 2;
            }

            //营销
            if($shop_info['market_day'] == 0)
            {
                $types[] = 4;
            }

            //课程【没有该字段余数，后面添加】
        }

        if(empty($types))
        {
            $this->success('获取数据成功','',['goods' => []]);
        }

        $goods = AddService::field('title,image,describe,num,unit_price,price,content,type')->where(['type' => ['in',$types],'status' => 1])->select();

        if($type == 1)
        {
            foreach ($goods as & $value)
            {
                if($value['type'] == 2)
                {
                    $value['end_date'] = date('Y-m-d',strtotime("+ {$shop_info['live_day']}day"));
                }
                else if($value['type'] == 4)
                {
                    $value['end_date'] = date('Y-m-d',strtotime("+ {$shop_info['market_day']}day"));
                }
            }
        }

        $data = [
            'goods' => $goods,
        ];

        $this->success('获取数据成功','',$data);
    }

    /**
     * 获取服务订购列表
     *
     * @ApiMethod (GET)
     * @ApiTitle    获取服务订购列表

     * @ApiSector   我的接口
     * @ApiReturn   ({
          "code": 1,
          "msg": "获取数据成功",
          "time": "1657984618",
          "data": null
        })
     */
    public function getServiceSubscription()
    {
        $user = $this->auth->getUserinfo();

        if(empty($user['shop_id']))
        {
            $this->error('非商家无权限');
        }

        $goods = AppreciationServe::field('title,price,basis_functions,remark,status,content,relation_id')->select();
        foreach ($goods as & $value) {
            $value['basis_functions'] = json_decode($value['basis_functions'],true);
        }

        $data = [
            'goods' => $goods,
        ];

        $this->success('获取数据成功','',$data);
    }

    /**
     * 获取我的订单列表
     *
     * @ApiMethod (GET)
     * @ApiTitle    获取我的订单列表

     * @ApiSector   我的接口
     * @ApiReturn   ({
          "code": 1,
          "msg": "获取数据成功",
          "time": "1657984618",
          "data": null
        })
     */
    public function getMyOrderList()
    {
        $user = $this->auth->getUserinfo();

        if(empty($user['shop_id']))
        {
            $this->error('非商家无权限');
        }

        $list = ManystoreOrderRecord::field('mor.sn,mor.pay_time,mor.pay_amount,mor.createtime,as.describe')
        ->alias('mor')
        ->join('ss_add_service as','as.id = add_service_id','left')
        ->where(['mor.shop_id' => $user['shop_id'],'mor.teacher_id' => $user['id']])
        ->select();

        foreach ($list as & $value) {
            $value['createtime'] = date('Y-m-d',$value['createtime']);

            if($value['pay_time'] > 0)
            {
                $value['status'] = 1;
            }
            else
            {
                $value['status'] = 0;
                $value['pay_amount'] = 0;
            }
            $value['pay_time'] = empty($value['pay_time']) ? '' : date('Y-m-d',$value['pay_time']);
        }

        $data = [
            'orders' => $list,
        ];

        $this->success('获取数据成功','',$data);
    }

    /**
     * 参与推荐有奖
     *
     * @ApiMethod (POST)
     * @ApiTitle    参与推荐有奖

     * @ApiParams (name="mechanism", type="string", required=false, description="机构名称")
     * @ApiParams (name="realname", type="string", required=false, description="联系人姓名")
     * @ApiParams (name="mobile", type="string", required=false, description="联系人手机号")

     * @ApiSector   我的接口
     * @ApiReturn   ({
          "code": 1,
          "msg": "获取数据成功",
          "time": "1657984618",
          "data": null
        })
     */
    public function toRecommend()
    {
        $user = $this->auth->getUserinfo();

        $mechanism = $this->request->post('mechanism');
        $realname = $this->request->post('realname');
        $mobile = $this->request->post('mobile');

        if(empty($mechanism))
        {
            $this->error(__('请填写机构名称'));
        }

        if(empty($realname))
        {
            $this->error(__('请填写联系人姓名'));
        }

        if (!$mobile || !\think\Validate::regex($mobile, "^1\d{10}$")) {
            $this->error(__('联系人手机号不正确'));
        }

        $count = ManystoreRecommendRecord::where('mechanism',$mechanism)->count();

        if($count > 0)
        {
            $this->error(__('该机构已有人推荐'));
        }

        $data = [
            'shop_id' => $user['shop_id'],
            'user_id' => $user['id'],
            'mechanism' => $mechanism,
            'realname' => $realname,
            'mobile' => $mobile,
            'createtime' => time(),
        ];

        // 启动事务
        Db::startTrans();
        try
        {
            ManystoreRecommendRecord::insert($data);

            // 提交事务
            Db::commit();
        }
        catch (\Exception $e)
        {
            // 回滚事务
            Db::rollback();
            $this->error('转介绍提交失败');
        }

        $this->success('转介绍提交成功','');
    }

    /**
     * 获取推荐有奖记录
     *
     * @ApiMethod (GET)
     * @ApiTitle    获取推荐有奖记录

     * @ApiSector   我的接口
     * @ApiReturn   ({
          "code": 1,
          "msg": "获取数据成功",
          "time": "1657984618",
          "data": null
        })
     */
    public function getRecommendRecord()
    {
        $user = $this->auth->getUserinfo();

        $list = ManystoreRecommendRecord::field('mrr.mechanism,mrr.realname,mrr.mobile,mrr.status,mrr.createtime,m.username as recommend_name')
        ->alias('mrr')
        ->join('ss_manystore m','m.id = mrr.user_id','left')
        ->where('mrr.shop_id',$user['shop_id'])
        ->select();

        $status_name = [0 => '有效',1 => '成功', 2 => '无效'];

        foreach ($list as & $value) {
            $value['createtime'] = date('Y-m-d',$value['createtime']);
            $value['status_name'] = isset($status_name[$value['status']]) ? $status_name[$value['status']] : '无效';
        }

        $data = [
            'count' => count($list),
            'list' => $list,
        ];

        $this->success('获取数据成功','',$data);
    }

    /**
     * 获取推荐获奖情况
     *
     * @ApiMethod (GET)
     * @ApiTitle    获取推荐获奖情况

     * @ApiParams (name="limit", type="integer", required=false, description="获取条数【默认20条】")

     * @ApiSector   我的接口
     * @ApiReturn   ({
          "code": 1,
          "msg": "获取数据成功",
          "time": "1657984618",
          "data": null
        })
     */
    public function getWinningRecord()
    {
        $user = $this->auth->getUserinfo();

        $limit = $this->request->param('limit');//获取条数
        $limit = empty($limit) || $limit <= 0 ? 20 : $limit;

        $list = ManystoreRecommendRecord::field('m.mobile')
        ->alias('mrr')
        ->join('ss_manystore m','m.id = mrr.user_id','left')
        ->where('mrr.status',1)
        ->order('mrr.createtime','desc')
        ->limit($limit)
        ->select();

        $data = ['count' => 0,'list' => []];

        foreach ($list as $value) {
            $data['list'][] = '尾号'.substr($value['mobile'], -4).'推荐成功!';
        }

        $data['count'] = count($data['list']);

        $this->success('获取数据成功','',$data);
    }

    /**
     * 获取员工列表
     *
     * @ApiMethod (GET)
     * @ApiTitle    获取员工列表（服务商、校区才能管理）

     * @ApiParams (name="page_num", type="integer", required=false, description="页码【从1开始】")
     * @ApiParams (name="page_count", type="integer", required=false, description="每页数据数【默认10】")
     * @ApiParams (name="is_teaching", type="integer", required=false, description="是否授课,0=否 其他=是")
     * @ApiParams (name="is_consultant", type="integer", required=false, description="是否为顾问,0=否 其他=是")
     * @ApiParams (name="is_quit", type="integer", required=false, description="是否离职,0=否 其他=是")
     * @ApiParams (name="search_key", type="string", required=false, description="搜索关键字【员工姓名、手机号】")

     * @ApiSector   我的接口
     * @ApiReturn   ({
          "code": 1,
          "msg": "获取数据成功",
          "time": "1657984618",
          "data": null
        })
     */
    public function getStaffList()
    {
        $user = $this->auth->getUserinfo();

        if($user['level'] > 1)
        {
            $this->error('无权限');
        }

        $param = $this->request->param();
        $page_num = empty($param['page_num']) ? 1 : intval($param['page_num']);
        $page_count = empty($param['page_count']) ? 10 : intval($param['page_count']);


        $map1 = $map2 = [];
        #搜索关键字【姓名/手机号】
        if(!empty($param['search_key']))
        {
            $map1['m.username'] = ['like',"%{$param['search_key']}%"];
            $map1['m.nickname'] = ['like',"%{$param['search_key']}%"];
            $map1['m.mobile'] = ['like',"%{$param['search_key']}%"];
        }

        if(!empty($param['is_teaching']))
        {
            $map2['m.teaching'] = 1;
        }

        if(!empty($param['is_consultant']))
        {
            $map2['m.course_consultant'] = 1;
        }

        if(!empty($param['is_quit']))
        {
            $map2['m.job_status'] = 0;
        }

        #查询线索数据总数
        $count = ManystoreModel::alias('m')
        ->where(function($query) use ($map1){
            if(!empty($map1))
            {
                $query->whereOr($map1);
            }
        })
        ->where(function($query) use ($map2){
            if(!empty($map2))
            {
                $query->where($map2);
            }
        })
        ->count();

        if($count <= 0)
        {
            $this->success('获取数据成功','',[]);
        }

        #最大页码
        $max_page_num = bcdiv($count,$page_count);
        if($count % $page_count > 0)
        {
            $max_page_num++;
        }

        if($page_num < 0)
        {
            $this->error('已经是第一页了');
        }

        if($page_num > $max_page_num)
        {
            $this->error('已经是最后一页了');
        }

        $limit_start_num = bcmul(bcsub($page_num,1),$page_count);


        $list = ManystoreModel::field('m.id AS staff_id,m.avatar,m.username,mag.name AS role')
        ->alias('m')
        ->join('ss_manystore_auth_group mag','mag.id = m.group_selfid')
        ->where(function($query) use ($map1){
            if(!empty($map1))
            {
                $query->whereOr($map1);
            }
        })
        ->where(function($query) use ($map2){
            if(!empty($map2))
            {
                $query->where($map2);
            }
        })
        ->limit($limit_start_num,$page_count)
        ->select();

        $data = ['count' => $count,'list' => $list];

        $this->success('获取数据成功','',$data);
    }

    /**
     * 获取员工信息
     *
     * @ApiMethod (GET)
     * @ApiTitle    获取员工信息（服务商、校区才能管理）

     * @ApiParams (name="staff_id", type="integer", required=false, description="员工ID")

     * @ApiSector   我的接口
     * @ApiReturn   ({
          "code": 1,
          "msg": "获取数据成功",
          "time": "1657984618",
          "data": null
        })
     */
    public function getStaffInfo()
    {
        $user = $this->auth->getUserinfo();

        if($user['level'] > 1)
        {
            $this->error('无权限');
        }

        $param = $this->request->param();

        if(empty($param['staff_id']))
        {
            $this->error('请选择要查看的员工');
        }

        $info = ManystoreModel::field('m.username,m.mobile,m.sex,m.teaching,m.course_consultant,m.goodsubjects,mi.*')
        ->alias('m')
        ->join('ss_manystore_information mi','mi.mid = m.id','left')
        ->where(['m.id' => $param['staff_id']]);

        //查询角色名称
        $role = ManystoreAuthGroup::where('id',$user['group_selfid'])->value('name');

        $data = [
            'name' => $info['username'],
            'mobile' => $info['mobile'],
            'sex' => $info['sex'],//性别:0=未选择,1=男,2=女
            'teaching' => $info['teaching'],//是否授课：0=否；1=是
            'course_consultant' => $info['course_consultant'],//是否课程顾问：0=否；1=是
            'goodsubjects' => !empty($info['goodsubjects']) ? explode(',', $info['goodsubjects']) : [],//擅长课程
            'role' => $role,
            'yearsteaching' => $info['yearsteaching'],
            'nickname' => $info['nickname'],
            'identity_card' => $info['identity_card'],
            'date_birth' => date('Y-m-d',$info['date_birth']),
            'current_address' => $info['current_address'],
            'place_domicile' => $info['place_domicile'],
            'contract_start' => date('Y-m-d',$info['contract_start']),
            'contract_end' => date('Y-m-d',$info['contract_end']),
            'obtainment_date' => date('Y-m-d',$info['obtainment_date']),
            'job_status' => empty($info['job_status']) ? 0 : 1,//在职状态：0=离职；1=在职
            'title' => $info['title'],//老师职称：1=正式；2=初级；3=中级；4=高级；5=资深
            'dimission_date' => date('Y-m-d',$info['dimission_date']),
            'image' => $info['image'],
            'face_image' => $info['face_image'],
            'identity_image' => $info['identity_image'],
            'education' => $info['education'],
            'labor_contract' => $info['labor_contract'],
            'other' => $info['other'],
            'hq' => $info['hq'],
            'personal' => $info['personal'],
            'remark' => $info['remark'],
        ];

        $this->success('获取数据成功','',$data);
    }


    /**
     * 编辑员工信息
     *
     * @ApiMethod (GET)
     * @ApiTitle    编辑员工信息（服务商、校区才能管理）

     * @ApiParams (name="staff_id", type="integer", required=true, description="员工ID")
     * 
     * @ApiParams (name="username", type="string", required=true, description="员工姓名")
     * @ApiParams (name="mobile", type="integer", required=true, description="手机号")
     * @ApiParams (name="sex", type="integer", required=false, description="性别,0=未选择,1=男,2=女")
     * @ApiParams (name="teaching", type="integer", required=false, description="是否授课,0=否；1=是")
     * @ApiParams (name="course_consultant", type="integer", required=false, description="是否顾问,0=否；1=是")
     * @ApiParams (name="goodsubjects", type="string", required=false, description="擅长科目ID【多项以逗号间隔】")
     * @ApiParams (name="group_selfid", type="integer", required=false, description="角色ID")
     * 
     * @ApiParams (name="yearsteaching", type="integer", required=false, description="教学年数")
     * @ApiParams (name="nickname", type="integer", required=false, description="昵称")
     * @ApiParams (name="identity_card", type="string", required=false, description="身份证号")
     * @ApiParams (name="date_birth", type="date", required=false, description="出生日期/年龄")
     * @ApiParams (name="current_address", type="string", required=false, description="现居住地")
     * @ApiParams (name="place_domicile", type="string", required=false, description="户籍地址")
     * @ApiParams (name="contract_start", type="date", required=false, description="合同开始日期")
     * @ApiParams (name="contract_end", type="date", required=false, description="合同结束日期")
     * @ApiParams (name="obtainment_date", type="date", required=false, description="转正日期")
     * @ApiParams (name="job_status", type="integer", required=false, description="在职状态：0=离职；1=在职")
     * @ApiParams (name="title", type="integer", required=false, description="老师职称：1=正式；2=初级；3=中级；4=高级；5=资深")
     * @ApiParams (name="dimission_date", type="date", required=false, description="离职日期")
     * @ApiParams (name="image", type="string", required=false, description="形象照")
     * @ApiParams (name="face_image", type="string", required=false, description="人脸照片")
     * @ApiParams (name="identity_image", type="string", required=false, description="身份证正反面照")
     * @ApiParams (name="education", type="string", required=false, description="学历证书")
     * @ApiParams (name="labor_contract", type="string", required=false, description="劳动合同")
     * @ApiParams (name="other", type="string", required=false, description="其他证件")
     * @ApiParams (name="hq", type="string", required=false, description="总部认证证书")
     * @ApiParams (name="personal", type="string", required=false, description="个人简介")
     * @ApiParams (name="remark", type="string", required=false, description="备注")

     * @ApiSector   我的接口
     * @ApiReturn   ({
          "code": 1,
          "msg": "获取数据成功",
          "time": "1657984618",
          "data": null
        })
     */
    public function editStaffInfo()
    {
        $user = $this->auth->getUserinfo();

        if($user['level'] > 1)
        {
            $this->error('无权限');
        }

        $param = $this->request->param();

        if(empty($param['staff_id']))
        {
            $this->error('请选择要编辑的员工');
        }

        $info = ManystoreModel::get($param['staff_id']);
        $detail = ManystoreInformation::where(['mid' => $param['staff_id']])->find();
        $info2 = [];
        if(empty($detail))
        {
            $info2 = [
                'shop_id' => $info['shop_id'],
                'mid' => $info['id'],
                'createtime' => time(),
                'updatetime' => time(),
            ];
        }

        if(empty($info))
        {
            $this->error('请选择要编辑的员工');
        }

        if(empty($param['username']))
        {
            $this->error('请填写员工姓名');
        }
        $info->username = $param['username'];

        if(!empty($param['mobile']) && !\think\Validate::regex($param['mobile'], "^1\d{10}$"))
        {
            $this->error('手机号不正确');
        }
        $info->mobile = $param['mobile'];

        if(isset($param['sex']) && $param['sex'] == 1)
        {
            $info->sex = 1;
        }
        else if(isset($param['sex']) && $param['sex'] == 2)
        {
            $info->sex = 2;
        }
        else
        {
            $info->sex = 0;
        }

        if(isset($param['teaching']))
        {
            $info->teaching = $param['teaching'] == 1 ? 1 : 0;
        }

        if(isset($param['course_consultant']))
        {
            $info->course_consultant = $param['course_consultant'] == 1 ? 1 : 0;
        }

        if(!empty($param['goodsubjects']))
        {
            $goodsubjects = explode(',', $param['goodsubjects']);
            $types = TypeModel::field('id')->where(['type' => 'goodsubjects','id' => ['in',$goodsubjects]])->select();
            $goodsubjects = [];
            foreach ($types as $tk => $tv)
            {
                $goodsubjects[] = $tv['id'];
            }

            if(!empty($goodsubjects))
            {
                $info->goodsubjects = implode(',', $goodsubjects);
            }
        }
        
        if(!empty($param['group_selfid']))
        {
            $role_id = ManystoreAuthGroup::where('id',$user['group_selfid'])->value('id');

            $info->group_selfid = $role_id;
        }

        if(isset($param['yearsteaching']))
        {
            if(intval($param['yearsteaching']) < 0)
            {
                $this->error('教学年数不能小于0');
            }

            $info2['yearsteaching'] = intval($param['yearsteaching']);
        }        

        if(!empty($param['nickname']))
        {
            $info2['nickname'] = $param['nickname'];
        }

        if(!empty($param['identity_card']))
        {
            if(!\think\Validate::regex($param['identity_card'], "^(\d{15}$)|(^\d{17}([0-9]|[xX]))$"))
            {
                $this->error('身份证号码错误');
            }

            $info2['identity_card'] = $param['identity_card'];
        }

        if(!empty($param['date_birth']))
        {
            $info2['date_birth'] = strtotime($param['date_birth']);
        }

        if(!empty($param['current_address']))
        {
            $info2['current_address'] = $param['current_address'];
        }

        if(!empty($param['place_domicile']))
        {
            $info2['place_domicile'] = $param['place_domicile'];
        }

        if(!empty($param['contract_start']))
        {
            $info2['contract_start'] = strtotime($param['contract_start']);
        }

        if(!empty($param['contract_end']))
        {
            $info2['contract_end'] = strtotime($param['contract_end']);
        }

        if(!empty($param['obtainment_date']))
        {
            $info2['obtainment_date'] = strtotime($param['obtainment_date']);
        }

        if(isset($param['job_status']))
        {
            $info2['job_status'] = $param['job_status'] == 1 ? 1 : 0;
        }

        if(isset($param['title']))
        {
            $info2['title'] = $param['title'] >= 1 && $param['title'] <= 5 ? $param['title'] : 1;
        }

        if(!empty($param['dimission_date']))
        {
            $info2['dimission_date'] = strtotime($param['dimission_date']);
        }

        if(!empty($param['image']))
        {
            $info2['image'] = $param['image'];
        }

        if(!empty($param['face_image']))
        {
            $info2['face_image'] = $param['face_image'];
        }

        if(!empty($param['identity_image']))
        {
            $info2['identity_image'] = $param['identity_image'];
        }

        if(!empty($param['education']))
        {
            $info2['education'] = $param['education'];
        }

        if(!empty($param['labor_contract']))
        {
            $info2['labor_contract'] = $param['labor_contract'];
        }

        if(!empty($param['other']))
        {
            $info2['other'] = $param['other'];
        }

        if(!empty($param['hq']))
        {
            $info2['hq'] = $param['hq'];
        }

        if(!empty($param['personal']))
        {
            $info2['personal'] = $param['personal'];
        }

        if(!empty($param['remark']))
        {
            $info2['remark'] = $param['remark'];
        }


        // 启动事务
        Db::startTrans();
        try
        {
            $info->save();

            if(empty($detail))
            {
                ManystoreInformation::insert($info2);
            }
            else if(!empty($info2))
            {
                ManystoreInformation::where(['mid' => $param['staff_id']])->update($info2);
            }

            // 提交事务
            Db::commit();
        }
        catch (\Exception $e)
        {
            // 回滚事务
            Db::rollback();
            echo '<pre>';
            print_r($e);
            exit;
            $this->error('编辑员工信息失败');
        }

        $this->success('编辑员工信息成功','');
    }

    /**
     * 删除员工信息
     *
     * @ApiMethod (GET)
     * @ApiTitle    删除员工信息（服务商、校区才能管理）

     * @ApiParams (name="staff_id", type="integer", required=false, description="员工ID")

     * @ApiSector   我的接口
     * @ApiReturn   ({
          "code": 1,
          "msg": "获取数据成功",
          "time": "1657984618",
          "data": null
        })
     */
    public function delStaffInfo()
    {
        $user = $this->auth->getUserinfo();

        if($user['level'] > 1)
        {
            $this->error('无权限');
        }

        $param = $this->request->param();

        if(empty($param['staff_id']))
        {
            $this->error('请选择要删除的员工');
        }

        $info = ManystoreModel::get($param['staff_id']);

        if(empty($info))
        {
            $this->error('请选择要删除的员工');
        }

        if($user['shop_id'] != $info['shop_id'])
        {
            $this->error('无权限操作非本校区员工');
        }

        // 启动事务
        Db::startTrans();
        try
        {
            $info->delete();

            // 提交事务
            Db::commit();
        }
        catch (\Exception $e)
        {
            // 回滚事务
            Db::rollback();
            $this->error('删除员工失败');
        }

        $this->success('删除员工成功','');
    }

}
